package com.tencent.hummingbird.portal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tencent.hummingbird.portal.exception.ServiceException;
import com.tencent.hummingbird.portal.mapper.UserMapper;
import com.tencent.hummingbird.portal.pojo.Comment;
import com.tencent.hummingbird.portal.mapper.CommentMapper;
import com.tencent.hummingbird.portal.pojo.User;
import com.tencent.hummingbird.portal.service.ICommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tencent.hummingbird.portal.vo.CommentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.rmi.ServerException;
import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yxb
 * @since 2024-01-10
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CommentMapper commentMapper;
    @Override
    public Comment postComment(String userName, CommentVO commentVO) {
        System.out.println("11111111111111111111111111111");
        User user = userMapper.findUserByUsername(userName);
        if(user==null){
            throw ServiceException.unprocesabelEntity("无对象");
        }
        Comment comment = new Comment();
        comment.setUserId(user.getId())
                .setAnswerId(commentVO.getAnswerId())
                .setContent(commentVO.getContent())
                .setCreatetime(LocalDateTime.now())
                .setUserNickName(user.getNickname());
        int result = commentMapper.insert(comment);
        if(result!=1){
            throw ServiceException.busy();
        }
        return comment;

    }

    @Override
    public void updateComment(Integer id, String content) {
        Comment comment = new Comment();
        comment.setId(id).setContent(content);
       int result =  commentMapper.updateComment(comment);
       if(result != 1) {
           throw ServiceException.busy();
       }
    }

    @Override
    public boolean removeComment(String username, Integer commentId) {
        User user = userMapper.findUserByUsername(username);
        if(user!=null&&user.getType()==1){
            int num1 = commentMapper.deleteById(commentId);
            return num1==1;
        }
        Comment comment = commentMapper.selectById(commentId);
        if(comment!=null&&comment.getUserId().equals(user.getId())){
            int num2 = commentMapper.deleteById(commentId);
            return num2==1;
        }
        throw ServiceException.invalidRequest("暂无权限");
    }


}
